package report;

import org.apache.jmeter.engine.util.NoThreadClone;
import org.apache.jmeter.samplers.Remoteable;
import org.apache.jmeter.samplers.SampleEvent;
import org.apache.jmeter.samplers.SampleListener;
import org.apache.jmeter.testelement.AbstractTestElement;
import org.apache.jmeter.testelement.TestStateListener;
import org.apache.jmeter.testelement.ThreadListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.concurrent.atomic.AtomicLong;

public class MyDelayListener extends AbstractTestElement
		implements Serializable, SampleListener, TestStateListener, Remoteable, ThreadListener, NoThreadClone {

	private static final Logger log = LoggerFactory.getLogger(MyDelayListener.class);

	private static AtomicLong deltaDelay = new AtomicLong(0);
	private static AtomicLong deltaCount = new AtomicLong(0);

	/**
	 *
	 * @return true代表停止增加线程，false代表继续增加线程
	 */
	public static boolean next() {
		if (deltaDelay.get() / deltaCount.get() > 250) {
			log.info("停止增加线程");
			return true;
		} else {
			deltaDelay.set(0);
			deltaCount.set(0);
			log.info("继续增加线程");
			return false;
		}
	}

	@Override
	public void sampleOccurred(SampleEvent e) {
		deltaCount.addAndGet(e.getResult().getSampleCount() + e.getResult().getErrorCount());
		deltaDelay.addAndGet(e.getResult().getLatency());
	}

	@Override
	public void sampleStarted(SampleEvent e) {

	}

	@Override
	public void sampleStopped(SampleEvent e) {

	}

	@Override
	public void testStarted() {

	}

	@Override
	public void testStarted(String host) {

	}

	@Override
	public void testEnded() {

	}

	@Override
	public void testEnded(String host) {

	}

	@Override
	public void threadStarted() {

	}

	@Override
	public void threadFinished() {

	}
}
